'use strict'

import { app, BrowserWindow,Menu,dialog } from 'electron'

import menu from './menu';
import config from "../renderer/config";
app.setAsDefaultProtocolClient('adtl');
/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}
global.__userDataPath = app.getPath('userData');

app.on('open-url', (event, url) => {
  dialog.showErrorBox('Welcome Back', `You arrived from: ${url}`)
  BrowserWindow.getAllWindows()[0].webContents.send('open.url',url);
})

let mainWindow
const winURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080`
  : `file://${__dirname}/index.html`
const  userAgent = "adtl/"+config.version;
function createWindow () {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    height: 800,
    useContentSize: true,
    width: 1300,
    userAgent: userAgent,
    webPreferences: {
      webSecurity: process.env.NODE_ENV !== 'development',
      nodeIntegration: true, // 是否集成 Nodejs,把之前预加载的js去了，发现也可以运行
    }
  })

  mainWindow.loadURL(winURL)
  mainWindow.webContents.openDevTools()
  mainWindow.webContents.setUserAgent(userAgent);
  mainWindow.on('closed', () => {
    mainWindow = null
  })
  if (process.env.NODE_ENV === 'development') {

    BrowserWindow.addDevToolsExtension(process.env.VUE_DEVTOOL_DIR);
  }
  //"/mnt/d/www/front_end/vue-devtools-4.1.5/shells/chrome"
}

app.on('ready', ()=>{
  Menu.setApplicationMenu(menu) // 设置菜单部分
  createWindow();
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})



app.on('browser-window-created', function () {
  let reopenMenuItem = findReopenMenuItem()
  if (reopenMenuItem) reopenMenuItem.enabled = false
})

app.on('window-all-closed', function () {
  let reopenMenuItem = findReopenMenuItem()
  if (reopenMenuItem) reopenMenuItem.enabled = true
  app.quit()
})


function findReopenMenuItem () {
  const menu = Menu.getApplicationMenu()
  if (!menu) return

  let reopenMenuItem
  menu.items.forEach(function (item) {
    if (item.submenu) {
      item.submenu.items.forEach(function (item) {
        if (item.key === 'reopenMenuItem') {
          reopenMenuItem = item
        }
      })
    }
  })
  return reopenMenuItem
}

